import random

from flask import Blueprint, request, json, jsonify
from comm import get_data

bp_course = Blueprint("course", __name__)

from db import db1


@bp_course.route('/couponM', methods=['POST', "GET", "PUT", 'DELETE'])
def couponM():
    # 添加
    if request.method == "POST":
        # 获取用户输入
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        # 构造sql语句
        sql = "insert into coupon values(0,'%s',%d,'%s','%s')" % (
            data['name'], int(data['total']), data['stime'], data['etime'])
        # pymysql
        db1.insert(sql)
        # 返回结果
        return 'ok'
    elif request.method == 'GET':
        id = request.args.get('id')
        sql = "select * from coupon where id=%d" % (int(id))
        res = db1.find(sql)
        return jsonify({"code": 200, 'coupon': res})

    elif request.method == 'PUT':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "update coupon set name='%s',total=%d,starttime='%s',endtime = '%s' where id = % d" % (
            data['name'], int(data['total']), data['stime'], data['etime'], int(data['id']))
        db1.insert(sql)
        return jsonify({"code": 200})

    elif request.method == 'DELETE':
        id = request.args.get('id')
        sql = "delete from coupon where id=%d" % (int(id))
        db1.insert(sql)
        return jsonify({"code": 200})


@bp_course.route('/deptM', methods=['POST', 'GET'])
def deptM():
    if request.method == "POST":
        data = get_data()
        # 判断名字是否已经存在
        sql = "select id from dept where name='%s'" % (data['name'])
        res = db1.find(sql)
        # 存在直接返回
        if res:
            return jsonify({"code": 10011, 'mes': '已经存在'})
        # 不存在添加
        else:
            sql = "insert into dept(name) values('%s')" % (data['name'])
            db1.insert(sql)
            return jsonify({"code": 200})
    else:
        sql = "select * from dept"
        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res})


from .myfile import myfile
import os


@bp_course.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    myfile.file_mkdir(2)
    file.save(os.path.join('./upload/2/', file.filename))
    return 'ok'


@bp_course.route('/scenicm', methods=['POST', 'GET'])
def scenicm():
    if request.method == "POST":
        data = request.form
        sql = "insert into scenic(title,price,typeid) values('%s',%.2f,%d)" % (
            data['title'], float(data['price']), int(data['typeid']))
        db1.insert(sql)
        sql1 = "select id from scenic where title='%s'" % (data['title'])
        res = db1.find(sql1)
        file = request.files['file']

        myfile.file_mkdir(str(res['id']))
        file.save(os.path.join('./static/upload/' + str(res['id']), file.filename))
        sql3 = "update scenic set pic='%s' where id=%d" % (
            '/static/upload/' + str(res['id']) + "/" + file.filename, int(res['id']))
        db1.insert(sql3)
        return jsonify({"code": 200})
    else:
        sql = 'select * from scenic'
        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res})


@bp_course.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    cityid = request.form['cityid']
    # 创建文件夹
    myfile.file_mkdir(cityid)
    # 图片上传
    file.save(os.path.join('./static/upload/' + str(cityid), file.filename))
    return jsonify({"code": 200, 'url': '/static/upload/' + str(cityid) + '/' + file.filename})


@bp_course.route('/citym')
def citym():
    sql = "select id,name from city"
    res = db1.findall(sql)
    return jsonify({"code": 200, 'list': res})


@bp_course.route('/prom', methods=['POST'])
def prom():
    data = get_data()
    sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')" % (
        data['title'], float(data['price']), int(data['city_id']), data['pic'])
    db1.insert(sql)
    return jsonify({"code": 200})

    sort = request.args.get('sort')
    if cityid == '0':
        sql = "select * from product order by price %s limit %d,%d" % (sort, start, page_size)
        sql1 = "select count(id) from product"
        res = db1.find(sql1)
        total = res['count(id)']
    else:
        sql = "select * from product where city_id=%d order by price %s limit %d"


@bp_course.route('/prom', methods=['POST', "GET"])
def prom():
    if request.method == "POST":
        data = get_data()
        sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')" % (
            data['title'], float(data['price']), int(data['city_id']), data['pic'])
        db1.insert(sql)
        return jsonify({"code": 200})
    else:
        page = request.args.get('page')
        page_size = 2
        start = (int(page) - 1) * page_size
        cityid = request.args.get('cityid')
        total = 0
        if cityid == '0':
            sql = "select * from product limit %d,%d" % (start, page_size)
            sql1 = "select count(id) from product"
            res = db1.find(sql1)
            total = res['count(id)']
        else:
            sql = "select * from product where city_id=%d limit %d,%d" % (int(cityid), start, page_size)
            sql1 = "select count(id) from product where city_id=%d" % (int(cityid))
            res = db1.find(sql1)
            total = res['count(id)']

        res = db1.findall(sql)
        return jsonify({"code": 200, 'list': res, 'total': total})


@bp_course.route('/cateM')
def cateM():
    sql = 'select * from yptype'
    res = db1.findall(sql)
    return jsonify({"code": 200, 'list': res})


# 获取记录接口
import datetime


@bp_course.route('/recordM')
def recordM():
    # 获取分类id
    id = request.args.get('typeid')
    if id == '0':
        sql = 'select * from record'
    else:
        sql = 'select * from record where typeid=%d' % (int(id))
    res = db1.findall(sql)
    list = []
    for i in res:
        dict = {'id': i['id'], 'stime': datetime.datetime.strftime(i['stime'], '%Y-%m-%d'),
                'etime': datetime.datetime.strftime(i['etime'], '%Y-%m-%d'), 'money': float(i['money'])}
        list.append(dict)
    return jsonify({"code": 200, 'list': list})


import datetime


@bp_course.route('/recordM')
def recordM():
    id = request.args.get('typeid')
    if id == '0':
        sql = 'select * from record'
    else:
        sql = 'select * from record where typeid=%d' % (int(id))
    res = db1.findall(sql)
    list = []
    for i in res:
        dict = {'id': i['id'], 'stime': datetime.datetime.strftime(i['stime'], '%Y-%m-%d'),
                'etime': datetime.datetime.strftime(i['etime'], '%Y-%m-%d'), 'money': float(i['money'])}
        list.append(dict)
    return jsonify({"code": 200, 'list': list})


@bp_course.route('/detailM')
def detailM():
    id = request.args.get('id')
    sql = "select * from record where id=%d" % (int(id))
    res = db1.find(sql)
    record = {'id': res['id'], 'stime': datetime.datetime.strftime(res['stime'], '%Y-%m-%d'),
              'money': float(res['money'])}
    return jsonify({'code': 200, 'record': record})


@bp_course.route('/orderM', methods=['GET', 'PUT'])
def orderM():
    if request.method == "PUT":
        id = request.args.get('id')
        sql = "select * from orders where id=%d" % (int(id))
        res = db1.find(sql)
        # 判断状态原来为1改成2，原来为2改成1
        status = 2
        if int(res['status']) == 2:
            status = 1

            # 执行更新操作
        sql1 = "update orders set status=%d where id=%d" % (status, int(id))
        db1.insert(sql1)
        return jsonify({"code": 200})

    else:
        # 当前页
        page = int(request.args.get('page'))
        # 每页显示多少条
        page_size = int(request.args.get('page_size'))
        start = (page - 1) * page_size
        sql = 'select * from orders limit %d,%d' % (start, page_size)
        res = db1.findall(sql)
        # 总条数
        sql1 = "select count(id) from orders"
        res1 = db1.find(sql1)
        return jsonify({"code": 200, 'list': res, 'total': res1['count(id)']})


def sendmoney():
    money = request.args.get('money')
    if not money:
        return jsonify({'code': 10011, 'mes': '必须输入金额'})
    else:
        try:
            money = float(money)
        except:
            return jsonify


import re
import time


@bp_course.route('/sendSms', methods=['POST'])
def sendSms():
    data = get_data()
    try:
        mobile = data['mobile']
    except:
        return jsonify({"code": 10010, "mes": '不能为空'})
    res = re.match('^1[3-9]\d{9}$', data['mobile'])
    if not res:
        return jsonify({"code": 10010, "mes": '手机号不合法'})
    sql = "select stime from trecord where mobile ='%s' order by id desc limit 1" % (str(mobile))
    record = db1.find(sql)
    if record:
        seconds = int(time.time()) - int(record['stime'])
        if seconds < 60:
            return jsonify({"code": 10012, "mes": '一分钟内不能发送'})
    code = random.randint(100000, 999999)
    sql2 = "insert into trecord(mobile,code,stime) values ('%s,%d,%d')" % (str(mobile), code, int(time.time()))
    db1.insert(sql2)
    return jsonify({"code": 200, "mes": '发送成功'})


@bp_course.route('/tlogin', methods=['POST'])
def tlogin():
    data = get_data()
    sql = "select code,stime from trecord where mobile='%s' order by id desc limit 0,1"
    res = db1.find(sql)
    if int(time.time()) - int(res('stime')) > 60:
        return jsonify({"code": 10020, "mes": '验证码已过期，重新发送'})
    if res['code'] == int(data['code']):
        sql1 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user = db1.find(sql1)
        if user:
            return jsonify({"code": 200, 'userid': user['id'], 'mes': '登陆成功'})
        sql2 = "insert into tuser(mobile) values('%s')" % (data['mobile'])
        db1.insert(sql2)
        sql3 = "select id from tuser where mobile='%s'" % (data['mobile'])
        user3 = db1.find(sql3)
        return jsonify({"code": 200, "userid": user3['id']})
    else:
        return jsonify({"code": 10021, "mes": '验证码输入错误'})
